package Util;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import Entidade.Usuario;

/**
 * Servlet Filter implementation class UsuarioFilter
 */
public class UsuarioFilter implements Filter {

	
	public static String entidade ="sistemaDarlan";
	/**
	 * Default constructor.
	 */
	public UsuarioFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpSession session = ((HttpServletRequest) request).getSession();
		if (session.getAttribute("UsuarioLogado") == null) {

			String loginUser = request.getRemoteUser();
			Usuario user = null;

			EntityManager manager = Persistence.createEntityManagerFactory(entidade).createEntityManager();

			//Query q = manager.createQuery("from Produto p");
			// sessao user
			Query use = manager.createQuery("from Usuario u where u.login = :login");
			use.setParameter("login", loginUser);

			user = (Usuario) use.getSingleResult();

			session.setAttribute("UsuarioLogado", user);

		}
		
		chain.doFilter(req,response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
